package game;


import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;

public class Grid {
	private int size;
	private Cell[][] cells;
	
	private Action seedAction = new AbstractAction() {
		@Override
		public void actionPerformed(ActionEvent event) {
			Cell uiCell = (Cell)event.getSource();
			if (uiCell.isAlive()) {
				uiCell.setAlive(false);
			} else {
				uiCell.setAlive(true);
			}
		}
	};
	
	public Grid(int size) {
		this.size = size;
		reset();
	}
	
	public void reset() {
		cells = new Cell[size][size];
		for (int i = 0; i < cells.length; i++) {
			for (int j = 0; j < cells[0].length; j++) {
				cells[i][j] = new Cell(seedAction);
			}
		}
	}

	public int neighbourCount(int x, int y) {
		return getNeighbours(x, y).size();
	}
	
	private List<Cell> getNeighbours(int x, int y) {
		List<Cell> neighbours = new ArrayList<Cell>();
		if (isAlive(x - 1, y - 1)) {
			neighbours.add(cells[x-1][y-1]);
		}
		if (isAlive(x - 1, y)) {
			neighbours.add(cells[x-1][y]);
		}
		if (isAlive(x - 1, y + 1)) {
			neighbours.add(cells[x-1][y+1]);
		}
		if (isAlive(x, y - 1)) {
			neighbours.add(cells[x][y-1]);
		}
		if (isAlive(x, y + 1)) {
			neighbours.add(cells[x][y+1]);
		}
		if (isAlive(x + 1, y - 1)) {
			neighbours.add(cells[x+1][y-1]);
		}
		if (isAlive(x + 1, y)) {
			neighbours.add(cells[x+1][y]);
		}
		if (isAlive(x + 1, y + 1)) {
			neighbours.add(cells[x+1][y+1]);
		}
		
		return neighbours;
	}
	
	private boolean isAlive(int x, int y) {
		boolean available = x >= 0 && y >= 0 && x < size && y < size;
		if (available) {
			return cells[x][y].isAlive();
		}
		
		return false;
	}

	public Cell[][] getCells() {
		return cells;
	}
}
